<template>
	<view>

		<st-mc-framework :navTitle="ModuleTitle" @changeLevel="changeLevel"
			@AddModuleData_select='AddModuleData_select'>

			<template #workbench>
				<m-drag-button :style="{ opacity: BtnShow ? 1 : 0 }" :isDock="true" :existTabBar="true"
					class="m-drag-button-view" :initialBottom="10">
					<template #BtnContent>
						<u-icon name="scan" color="#fff" size="25px" @click="scan"></u-icon>
					</template>
				</m-drag-button>
				<m-drag-button :style="{ opacity: BtnShow ? 1 : 0 }" :isDock="true" :existTabBar="true"
					class="m-drag-button-view" :initialBottom="60">
					<template #BtnContent>
						<u-icon name="plus" color="#fff" size="25px" @click="add"></u-icon>
					</template>
				</m-drag-button>
				<m-drag-button :style="{ opacity: BtnShow ? 1 : 0 }" :isDock="true" :existTabBar="true"
					class="m-drag-button-view" :initialBottom="110">
					<template #BtnContent>
						<u-icon name="search" color="#fff" size="25px" @click="search"></u-icon>
					</template>
				</m-drag-button>


			</template>
			<template #content>
				<view class="content_box f-dc">

					<view class="table table_top_th">
						<table>
							<tr>
								<th width='15%'>报废单号</th>
								<th width='15%'>报废模具</th>
								<th width='20%'>报废时间</th>
								<th width='20%'>报废类型</th>
								<th width='10%'>报废人</th>
								<th width='20%'>报废原因</th>
							</tr>
						</table>
					</view>
					<z-paging ref="paging" v-model="dataList" @query="queryList" :fixed="false" class="z_paging">

						<view class="table">
							<table class="table-full">

								<tbody>
									<tr v-for="(item,index) in dataList" :key="index" @click="itemClick(item,index)">
										<td width='15%'>
											<view class="newlineDiv"><text>{{item.BillNO}}</text></view>
										</td>
										<td width='15%'>
											<view class="newlineDiv"><text>{{item.MoludName}}</text></view>
										</td>
										<td width='20%'>
											<view class="newlineDiv"><text>{{item.BillDate }}</text></view>
										</td>
										<td width='20%'>
											<view class="newlineDiv"><text>{{item.ScrapType}}</text></view>
										</td>
										<td width='10%'>
											<view class="newlineDiv"><text>{{item.BFMan}}</text></view>
										</td>
										<td width='20%'>
											<view class="newlineDiv"><text>{{item.BFCause}}</text></view>
										</td>

									</tr>
								</tbody>
							</table>
						</view>
					</z-paging>
				</view>


				<uni-popup ref="popup" type="bottom" background-color="#fff" border-radius="10px 10px 0 0"
					@change="changePopup">
					<view class="popup_content">

						<u-cell-group :border='false'>
							<u-cell title="模具 " :isLink="false">
								<view slot="value" style="width: 20%;" @click="openBaseScreen('模具')">
									<u-input v-model="FormData.MoludName" placeholder="请选择" readonly
										clearable></u-input>
								</view>
							</u-cell>
							<u-cell title="开始时间" :isLink="false" :value='FormData.FBDate'
								@click="addTime('开始')"></u-cell>
							<u-cell title="结束时间" :isLink="false" :value='FormData.FEDate'
								@click="addTime('结束')"></u-cell>

						</u-cell-group>
						<view class="bottomBtns">
							<button block @click="submit">
								查 &nbsp &nbsp &nbsp &nbsp &nbsp &nbsp &nbsp &nbsp &nbsp &nbsp &nbsp 询
							</button>
						</view>

					</view>
				</uni-popup>


			</template>

		</st-mc-framework>
		<u-datetime-picker :show="show" v-model="value1" mode="date" @cancel='show = false'
			@confirm='pickerConfirm'></u-datetime-picker>

		<m-loading :text="loadingName" v-model="showMLoading" :showClose="false"
			maskBackgroundColor="rgba(0,0,0,0.3)"></m-loading>
	</view>
</template>

<script>
	import {
		getTimeStamp,
		getFormatDateTime,
		getBefore7DateTime,
		formatDateTime,
		navigateMixin,
		baseAddModuleData_select,
		getchangeLevel
	} from '@/st_mes_zs/common/base.js';

	export default {
		mixins: [navigateMixin, baseAddModuleData_select],
		data() {
			return {
				dataList: [],
				FormData: {
					FWorkshopID: 0,
					PageIndex: 1,
					PageSize: 30,
					FBDate: '',
					FEDate: '',
					BYStatus: -1,
					MoludName: ''
				},
				APPFunID: 0,
				tabIndex: 0,
				showLeft: false,
				TimeName: '',
				show: false,
				value1: Number(new Date()),

				BYStatusList: [{
						name: '全部',
						id: -1,
						checked: true
					}, {
						name: '未开始保养',
						id: 0,
						checked: false
					},
					{
						name: '保养中',
						id: 1,
						checked: false
					},
					{
						name: '已结束保养',
						id: 2,
						checked: false
					}
				],
				disabled: false,
				ModuleTitle: '', //标题名称
				showMLoading: false, //是否加载
				loadingName: '正在加载中……', //加载名称
				BtnShow: false, //按钮显示
				FWorkshopID: 0,
			}

		},

		onShow() {
			var that = this
			uni.$on('refreshList', () => {
				this.getList(); // 调用目标方法
			});
		},
		onUnload() {
			uni.$off('refreshList');
		},
		onReady() {
			var that = this
			uni.hideLoading();
			that.showMLoading = true
			const {
				GuyueModule,
				UserInfo,
				appConfigInfo
			} = that.$store.state;
			const {
				MesBasicInfo
			} = GuyueModule;


			that.FWorkshopID = MesBasicInfo.FWorkshopID;
			that.ModuleTitle = appConfigInfo.ActiveModule.ModuleName

			that.$nextTick(() => {
				setTimeout(() => {
					that.BtnShow = true;
				}, 500)
			})
		},
		onLoad(options) {
			var that = this
			that.$safeStatus({
				payload: '其他', // 要传递的数据
			});
			const {
				GuyueModule,
				UserInfo,
				appConfigInfo
			} = that.$store.state;
			const {
				MesBasicInfo
			} = GuyueModule;
			if (options.Dispatchitem) {
				const dispatchItem = JSON.parse(options.Dispatchitem);
				that.assignFormData(that.FormData, dispatchItem);
				return;
			}
			const formDefaults = {
				FBDate: getBefore7DateTime(),
				FEDate: getFormatDateTime(new Date()),
			};
			that.assignFormData(that.FormData, formDefaults);
		},
		onShow() {
			var that = this
			uni.$on('refreshDetail', (res) => {
				that.getValue(res.data); // 调用目标方法
			});
		},
		onUnload() {
			uni.$off('refreshDetail');
		},
		methods: {
			getValue(payload) {
				var that = this;
				that.showMLoading = false
				const {
					type,
					...data
				} = payload;
				if (payload === '返回') return;
				const typeHandlers = {
					'模具': () => ({
						MoldID: data.MoludID,
						MoludName: data.MoludCode
					}),
				};
				if (typeHandlers[type]) {
					Object.assign(this.FormData, typeHandlers[type]());
				}
			},
			openBaseScreen(str) {
				var that = this;
				var obj;
				if (str == '模具') {
					obj = {
						cmd: 'ZS_Droplist_Molud',
						type: str,
						serverSearch: {
							isPaging: true, //是否分页
							pageIndexStr: 'PageIndex', //分页页码字段，应包含在param中		
							searchShow: false, //是否查询
							searchKey: 'searchKey', //搜索关键词，应包含在param中
							showText: 'MoludCode', //查询结果显示的字段
						},
						param: {
							MoludID: 0,
							FWorkshopID: that.FWorkshopID,
							MoludCode: '',
							PageIndex: 1,
							PageSize: 30
						}
					}
				}
				uni.navigateTo({
					url: `../common/baseScreen?obj=${JSON.stringify(obj)}`,
					animationType: 'slide-in-right',
					animationDuration: 300
				});


			},

			scan() {
				var that = this
				this.$scanPopup.openScan({
					success: (res) => {
						console.log(res);
						var jobid = res.result.replace(/^.*?\|/, '')
						console.log(jobid);
						var obj = {
							MoludID: jobid,
							FWorkshopID: that.FWorkshopID,
							MoludCode: '',
							PageIndex: 1,
							PageSize: 30
						}
						that.Request.request('ZS_Droplist_Molud', obj, (ret) => {
							console.log(ret);
							if (ret.status == 200) {
								var Detailsitem = ret.data.ds[0]
								let routes = getCurrentPages();
								var url =
									`/st_mes_zs/mold/moldscrapDetail?Detailsitem=${JSON.stringify(Detailsitem)}`
								let obj = {
									path: 'manual',
									Name: '模具报废详情',
									APPFunID: '模具报废详情',
									length: routes.length + 1,
									url: url
								}
								that.GonavigateTo(obj, url)
							}
						})
					}
				})
			},
			// 创建表单赋值工具函数
			assignFormData(target, defaults = {}) {
				var that = this;
				Object.keys(defaults).forEach(key => {
					target[key] = defaults[key];
				});
				that.$forceUpdate();
			},
			radioClick(item, idx) {
				let that = this;
				this.BYStatusList.map((item, index) => {
					item.checked = index === idx ? true : false
				})
				const formDefaults = {
					BYStatus: item.id
				}
				that.assignFormData(that.FormData, formDefaults);
				this.contents = [];
				this.$refs.paging.reload();
			},
			getList() {
				this.contents = []; // 假设这是异步获取数据的操作
				this.$refs.paging.reload();
			},


			addTime(name) {
				this.TimeName = name
				if (this.TimeName == '开始') {
					this.value1 = Number(getTimeStamp(this.FormData.FBDate))
				} else {
					this.value1 = Number(getTimeStamp(this.FormData.FEDate))
				}
				this.show = true
			},

			pickerConfirm(e) {
				var time = getFormatDateTime(e.value)
				var formDefaults = {}
				if (this.TimeName == '开始') {
					formDefaults = {
						FBDate: time
					};

				} else {
					formDefaults = {
						FEDate: time
					};
				}
				this.assignFormData(this.FormData, formDefaults);
				this.show = false
			},
			changePopup() {

			},
			search() {
				this.$refs.popup.open('bottom')

			},
			submit() {

				this.$refs.popup.close('bottom')
				this.contents = []; // 假设这是异步获取数据的操作
				this.$refs.paging.reload();
			},
			add() {
				let that = this;
				let routes = getCurrentPages();
				var url = '/st_mes_zs/mold/moldscrapDetail'
				let obj = {
					path: 'manual',
					Name: '模具报废详情',
					APPFunID: '模具报废详情',
					length: routes.length + 1,
					url: url

				}
				this.GonavigateTo(obj, url)
			},
			queryList(pageNo) {
				let that = this;
				that.FormData.PageIndex = pageNo
				try {
					console.log(that.FormData);
					that.Request.request('getScrapMouldList', that.FormData, (ret) => {
						console.log(ret);
						that.showMLoading = false
						if (ret.status == 200) {
							ret.data.ds.map((item) => {
								item.BillDate = item.BillDate ? item.BillDate.split('T')[0] : ''

							})
							that.$refs.paging.complete(ret.data.ds);
						}
					}, (err) => {
						that.showMLoading = false
					})
				} catch (e) {
					console.log(e)
					that.showMLoading = false
					this.$utils.hideLoading();
					this.$utils.msg('请求失败请重试')
				}
			},

			itemClick(item, index) {
				let routes = getCurrentPages();
				var url = `/st_mes_zs/mold/moldscrapDetail?ScrapMould=${item.ScrapMould}`
				let obj = {
					path: 'manual',
					length: routes.length + 1,
					Name: '模具报废详情',
					APPFunID: '模具报废详情',
					url: url,
				}
				this.GonavigateTo(obj, url)
			},

			GonavigateTo(obj, url) {
				let that = this;
				var initData = JSON.parse(JSON.stringify(that.$store.state.GuyueModule.ModuleData_select));
				var parentData = initData[initData.length - 1]
				parentData.url = `/st_mes_zs/mold/moldscraplist?Dispatchitem=${JSON.stringify(that.FormData)}`;
				that.$modifyParentData(parentData);
				this.$safeNavigate({
					targetUrl: url, // 目标页面路径
					payload: obj, // 要传递的数据
				});
			},
			async AddModuleData_select(res) {
				try {
					const backDelta = await this.GetModuleData_select(res);
				} catch (error) {
					console.error('返回操作失败:');
				}
			},
			changeLevel(list, data, row) {
				getchangeLevel(data)

			},
		},


		onNavigationBarButtonTap(e) {
			if (this.showLeft) {
				this.$refs.showLeft.close()
			} else {
				this.$refs.showLeft.open()
			}
		},
		// app端拦截返回事件 ，仅app端生效
		onBackPress() {
			if (this.showRight || this.showLeft) {
				this.$refs.showLeft.close()
				this.$refs.showRight.close()
				return true
			}
		}
	}
</script>

<style lang="scss">
	@import "../css/index.css";

	.active-row-yellow text {
		color: #fcc105;
	}

	.inactive-row-green text {
		color: green;
	}
</style>